<template>
  <div class="page-common-layout custom-knowledgeBase-container">
    <!-- 查询条件 -->
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <AssociativeSelectGroup
            :map="selectMap"
            @conditionChange="selectGroupChange($event)"
          >
          </AssociativeSelectGroup>
        </template>
        <template slot="operate">
          <a-button
            @click="handelExport()"
            type="primary"
            icon="cloud-download"
          >
            导出
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="result-body-warp">
      <!-- 项目资料库 -->
      <div class="drawing-container">
        <div class="header">
          {{ menuName }}
          <!-- <icon-font
            class="add-file-button"
            type="icon-qianfazhengshu"
            @click="handleAAA()"
          ></icon-font> -->
          <icon-font
            class="add-file-button"
            type="icon-xinjianwenjianjia"
            @click="handleTreeAdd({ pid: '0' }, 1)"
            v-action:xmzlk_add
          ></icon-font>
        </div>
        <div class="condition">
          <a-input placeholder="请输入关键字" v-model="keyWord" />
          <div class="search-btn">
            <a-icon type="search" @click="handleFilterTree()" />
          </div>
        </div>
        <div class="tree-container">
          <a-empty v-if="treeData.length == 0" :description="false" />
          <a-tree
            v-else
            v-model="checkedKeys"
            show-icon
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            :replaceFields="{
              children: 'childList',
              title: 'nodeName',
              key: 'uuid',
            }"
            @expand="onExpand"
            @select="onSelect"
          >
            <!-- 自定义图标 -->
            <template slot="custom">
              <icon-font type="icon-wenjianjia-" />
            </template>
            <template
              slot="title"
              slot-scope="{ nodeName, uuid, pid, deleteFlag }"
            >
              <div class="custom-tree-title-warp">
                <div class="title">
                  {{ nodeName }}
                </div>
                <div class="operate">
                  <!-- 新增 -->
                  <icon-font
                    type="icon-xinjianwenjianjia"
                    class="add-file-button"
                    @click.stop="handleTreeAdd({ pid: uuid }, 1)"
                    v-action:xmzlk_add
                  ></icon-font>
                  <!-- 编辑 -->
                  <a-icon
                    type="edit"
                    class="edit-btn"
                    @click.stop="handleTreeAdd({ nodeName, uuid, pid }, 2)"
                    v-action:xmzlk_edit
                  />
                  <!-- 删除 -->
                  <a-icon
                    v-if="deleteFlag"
                    type="delete"
                    class="delete-btn"
                    @click.stop="handleDelClick({ uuid }, 1)"
                    v-action:xmzlk_delete
                  />
                </div>
              </div>
            </template>
          </a-tree>
        </div>
      </div>
      <!-- 列表 -->
      <div class="right-container">
        <div class="header">
          <div class="operate-condition-warp">
            <a-button
              type="primary"
              icon="plus"
              :disabled="!currentTreeNode.uuid"
              @click="handleTableAdd({}, 1)"
              v-action:xmzlk_add
            >
              新增
            </a-button>
          </div>
          <div class="search-condition-warp">
            <div class="condition-warp">
              <a-input
                placeholder="请输入文件名称"
                v-model="condition.fileName"
                style="width:180px"
              />
              <a-select
                style="width: 180px"
                v-model="condition.type"
                placeholder="请选择类别"
                showSearch
                allowClear
                :filter-option="filterOption"
              >
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in typeSource"
                  :key="item.dicItemCode"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
              <a-date-picker
                mode="year"
                format="YYYY"
                valueFormat="YYYY"
                v-model="condition.year"
                :open="condition.isopen"
                placeholder="选择年份"
                @panelChange="yearPanel"
                @openChange="yearOpen"
                class="year-picker"
              />
            </div>
            <div class="button-warp">
              <a-button type="primary" icon="search" @click="handleSearch()">
                查询
              </a-button>
              <a-button icon="sync" @click="handleReset()">重置</a-button>
            </div>
          </div>
        </div>
        <div class="table-container">
          <!-- table -->
          <vxe-table
            ref="xTable"
            height="99%"
            align="center"
            show-overflow
            show-header-overflow
            border="inner"
            :data="tableData"
            :column-config="{ resizable: true }"
            size="small"
            :loading="tableLoading"
          >
            <vxe-column type="seq" width="80" title="序号"></vxe-column>
            <vxe-column field="fileCode" width="80" title="编号"></vxe-column>
            <vxe-column title="名称" field="fileName" min-width="150">
            </vxe-column>
            <vxe-column title="查看/下载" width="100">
              <template #default="{ row }">
                <!-- 预览 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon
                    type="eye"
                    class="preview-btn"
                    @click="previewFile(row)"
                  />
                </a-tooltip>
                <!-- 下载 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    下载
                  </template>
                  <a-icon
                    type="download"
                    class="download-btn"
                    @click="downloadFile(row)"
                  />
                </a-tooltip>
              </template>
            </vxe-column>
            <vxe-column field="fileTypeDesc" title="类别"> </vxe-column>
            <vxe-column field="sort" width="80" title="排序号"></vxe-column>
            <vxe-column field="createTime" title="创建时间"> </vxe-column>
            <vxe-column field="creator" title="创建人" width="100">
            </vxe-column>
            <vxe-column title="状态" width="100">
              <template #default="{ row }">
                <span :class="[checkClassName(row.status), 'status']">
                  {{ checkStatusName(row.status) }}
                </span>
              </template>
            </vxe-column>
            <vxe-column field="operate" title="操作" fixed="right" width="120">
              <template #default="{ row }">
                <template v-if="row.status == 0">
                  <!-- 归档 -->
                  <a-tooltip placement="top" v-action:xmzlk_file>
                    <template slot="title">
                      归档
                    </template>
                    <icon-font
                      type="icon-guidang"
                      class="file-btn"
                      @click.stop="handeFile(row)"
                    ></icon-font>
                  </a-tooltip>
                  <!-- 编辑 -->
                  <a-tooltip placement="top" v-action:xmzlk_edit>
                    <template slot="title">
                      编辑
                    </template>
                    <a-icon
                      type="edit"
                      class="edit-btn"
                      @click="handleTableAdd(row, 2)"
                    />
                  </a-tooltip>
                  <!-- 删除 -->
                  <a-tooltip placement="top" v-action:xmzlk_delete>
                    <template slot="title">
                      删除
                    </template>
                    <a-icon
                      type="delete"
                      class="delete-btn"
                      @click="handleDelClick(row, 2)"
                    />
                  </a-tooltip>
                </template>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <!-- 分页 -->
        <div class="pager-container">
          <vxe-pager
            size="small"
            background
            :current-page.sync="pager.page"
            :page-size.sync="pager.pageSize"
            :total="pager.total"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
            :page-sizes="[20, 50, 100, 500]"
            @page-change="paginationChange"
          >
            <template #left>
              <div class="vxe-pager-left-tip-container">
                共<span>{{ pager.total }}</span
                >条
              </div>
            </template>
          </vxe-pager>
        </div>
      </div>
    </div>

    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>

    <!-- 树弹窗 -->
    <addTreeModal
      :visible.sync="addTreeModal.visible"
      :operateType="addTreeModal.operateType"
      :parameter="addTreeModal.soucre"
    ></addTreeModal>
    <!-- 表格弹窗 -->
    <addTableModal
      :visible.sync="addTableModal.visible"
      :operateType="addTableModal.operateType"
      :parameter="addTableModal.soucre"
    ></addTableModal>
  </div>
</template>

<script>
// 标准规范库
import moment from "moment";
import cloneDeep from "lodash.clonedeep";
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
import { mapGetters } from "vuex";
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";
import {
  downloadDfs,
  getToken,
  downLoadBatchFileByArraybuffer,
} from "@/utils/TopVUI";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import AssociativeSelectGroup from "@/components/extendCustom/AssociativeSelectGroup";
//附件
import previewModal from "@/pages/document/minio/previewModal";
//树弹窗
import addTreeModal from "./components/addTreeModal.vue";
//列表弹窗
import addTableModal from "./components/addTableModal.vue";
import { getDicItemByCode } from "@/api/common.js";
import {
  getMaterialTreeList,
  getMaterialPage,
  deleteTreeMaterial,
  deleteTableMaterial,
  exportBaseExcel,
  archiveBase,
} from "@/api/knowledgeBase";
export default {
  components: {
    IconFont,
    ScreenConditions,
    AssociativeSelectGroup,
    addTreeModal,
    addTableModal,
    previewModal,
  },
  data() {
    return {
      selectMap: [
        //项目
        {
          type: "proCode",
          mode: "default",
          placeholder: "请选择项目",
          isDefault: true,
          allowClear: false,
        },
      ],
      conditionsData: {},
      //查询体条件
      condition: {
        //文件名称
        fileName: "",
        //类别
        type: undefined,
        //日期范围
        year: null,
        isopen: false,
      },
      //项目资料库
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      cloneTreeData: [],
      currentTreeNode: {},
      keyWord: "",
      //table
      tableData: [],
      tableLoading: false,
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      //树
      addTreeModal: {
        visible: false,
        operateType: 1,
        soucre: {},
      },
      //表格
      addTableModal: {
        visible: false,
        operateType: 1,
        soucre: {},
      },
      //编辑
      visible: false,
      confirmLoading: false,
      url: {
        save: "/form/formDatabase/formSave",
        update: "/form/formDatabase/formUpdate",
      },
      tableDataType: "",
      tableUuid: "",
      modalFooter: {},
      //额外传参
      extraForm: {},
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //类别
      typeSource: [],
      //页面类型
      pageType: 3,
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },

  mounted() {
    this.getTypeSelectData();
  },
  methods: {
    handleAAA() {
      let { proCode } = this.conditionsData;
      this.$post(
        `/probusiness/archiveDirectory/createDirectory?proCode=${proCode}&type=100`,
        {},
        {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
          },
        }
      )
        .then((res) => {
          this.getTreeData();
        })
        .catch((_) => {});
    },

    deleteTreeMaterial,
    deleteTableMaterial,
    //导出
    handelExport() {
      let { proCode } = this.conditionsData;
      exportBaseExcel({ tenantCode: proCode })
        .then((data) => {
          downLoadBatchFileByArraybuffer(data, "项目资料库");
        })
        .catch((_) => {});
    },
    //归档
    handeFile(row) {
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定文件是否归档？归档之后不可操作！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          archiveBase({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },
    //预览
    previewFile(row) {
      let list = this.analysisPath(row.files);
      let { url } = list?.[0] ?? {};
      if (!url) {
        this.$message.warning("文件不存在", 1.5);
        return;
      }
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    //下载
    downloadFile(row) {
      let list = this.analysisPath(row.files);
      let { url } = list?.[0] ?? {};
      if (!url) {
        this.$message.warning("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },
    analysisPath(files = "[]") {
      let list = JSON.parse(files ?? "[]");
      return list;
    },
    //树【新增、编辑】
    handleTreeAdd(row = {}, type) {
      let { proCode } = this.conditionsData;
      this.addTreeModal.soucre = { ...row, tenantCode: proCode };
      this.addTreeModal.operateType = type;
      this.addTreeModal.visible = true;
    },
    //表格【新增、编辑】
    handleTableAdd(row = {}, type) {
      let { uuid, tenantCode } = this.currentTreeNode;
      this.addTableModal.soucre = { ...row, tenantCode, directoryUuid: uuid };
      this.addTableModal.operateType = type;
      this.addTableModal.visible = true;
    },
    //删除
    handleDelClick(row, type) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          let apiUrl = "";
          switch (type) {
            //树删除
            case 1:
              apiUrl = "deleteTreeMaterial";
              break;
            //列表删除
            case 2:
              apiUrl = "deleteTableMaterial";
              break;
            default:
              break;
          }
          that[apiUrl]({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (type == 1) {
                  that.getTreeData();
                }
                if (type == 2) {
                  if (dataLength == 1 && that.pager.page > 1) {
                    that.pager.page -= 1;
                  }
                  that.getTableData();
                }
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //监听树形选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.pager.page = 1;
      this.getTableData();
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //查询类别下拉框
    getTypeSelectData() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "projectInformationType" })
          .then((res) => {
            let { data } = res;
            this.typeSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.typeSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询项目列表-树形
    getTreeData() {
      return new Promise((resolve, reject) => {
        let { proCode } = this.conditionsData;
        getMaterialTreeList({ tenantCode: proCode })
          .then((res) => {
            let { data } = res;
            this.cloneTreeData = cloneDeep(data ?? []);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              this.cloneTreeData,
              "childList"
            );
            this.treeData = filterData ?? [];
            this.tableData = [];
            this.treeData.length > 0 && this.getFirstTreeNode();
            resolve();
          })
          .catch((_) => {
            this.cloneTreeData = [];
            this.treeData = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //默认展开第一级节点
    getFirstTreeNode() {
      let { treeData } = this;
      let flatData = flatTreeData(treeData, "childList");
      let item = flatData.find((v) => !v.childList || v.childList.length == 0);
      this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
      this.selectedKeys = [item.uuid];
      this.currentTreeNode = item;
      this.pager.page = 1;
      this.getTableData();
    },

    //查询分页数据
    getTableData() {
      this.tableLoading = true;
      let { page, pageSize } = this.pager;
      let { uuid } = this.currentTreeNode;
      let { fileName, type = "", year = "" } = this.condition;
      getMaterialPage({
        page,
        pageSize,
        pid: uuid,
        fileName,
        type,
        year,
      })
        .then((res) => {
          this.tableData = res?.rows || [];
          this.pager.total = res?.totalCount || 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.tableLoading = false;
        });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },
    handleSearch() {
      this.pager.page = 1;
      this.getTableData();
    },
    handleReset() {
      this.condition.fileName = "";
      this.condition.type = undefined;
      this.condition.year = "";
      this.handleSearch();
    },
    //选择年份
    yearPanel(e) {
      this.condition.year = moment(e).format("YYYY");
      this.condition.isopen = false;
    },
    yearOpen(status) {
      if (status) {
        this.condition.isopen = true;
      } else {
        this.condition.isopen = false;
      }
    },

    //查询图纸管理树
    handleFilterTree() {
      let { keyWord, cloneTreeData } = this;
      let cloneData = cloneDeep(cloneTreeData);
      this.treeData = this.filterTree(cloneData, "childList", (node) =>
        node.nodeName.includes(keyWord)
      );
    },
    //过滤树形数据
    filterTree(data, children = "children", filterFunc) {
      return data
        .filter((node) => {
          // 如果当前节点符合条件，直接返回true
          if (filterFunc(node)) {
            return true;
          }
          // 如果当前节点有子节点，递归过滤子节点
          if (node[children]) {
            node[children] = this.filterTree(
              node[children],
              children,
              filterFunc
            );
            // 如果过滤后的子节点不为空，说明当前节点需要保留
            return node[children].length > 0;
          }
          // 当前节点不符合条件，也没有子节点或子节点不符合条件，返回false
          return false;
        })
        .map((node) => {
          // 创建新对象，避免修改原始数据
          return {
            ...node,
            [children]: node[children]
              ? this.filterTree(node[children], children, filterFunc)
              : [],
          };
        });
    },

    checkStatusName(status) {
      switch (status) {
        case 0:
          return "未归档";
        case 1:
          return "已归档";
        default:
          return "";
      }
    },
    checkClassName(status) {
      switch (status) {
        case 0:
          return "default";
        case 1:
          return "progress";
        default:
          return "";
      }
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    selectGroupChange(data) {
      this.dealConditionsData(data);
      this.getTreeData();
    },

    //处理搜索区域选中值
    dealConditionsData(data = {}) {
      Object.keys(data).forEach((key) => {
        if (!data[key]) {
          this.conditionsData[key] = "";
        } else if (Array.isArray(data[key])) {
          this.conditionsData[key] = data[key]
            .map((v) => v.key)
            .filter((v) => v)
            .toString();
        } else if (
          Object.prototype.toString.call(data[key]) === "[object Object]"
        ) {
          this.conditionsData[key] = data[key].key;
        } else {
          this.conditionsData[key] = "";
        }
      });
    },

    moment,
  },
};
</script>

<style lang="less" scoped></style>
